package com.itqf.service.impl;

import com.itqf.dao.CarDao;
import com.itqf.dao.OrderDao;
import com.itqf.dao.impl.CarDaoImpl;
import com.itqf.dao.impl.OrderDaoImpl;
import com.itqf.entity.Car;
import com.itqf.entity.Item;
import com.itqf.entity.Order;
import com.itqf.service.OrderService;
import com.itqf.utils.RandomUtils;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    @Override
    public void createOrder(String aid, String userno, String sum) throws IllegalAccessException, SQLException, InvocationTargetException {
        Order order = new Order();
        BigDecimal count = new BigDecimal(sum);
        String orderId = RandomUtils.createOrderId();
        order.setOid(orderId);
        order.setAddressid(Integer.parseInt(aid));
        order.setUserno(Integer.parseInt(userno));
        order.setOtime(new Date());
        order.setCount(count);
        order.setOstatus(1);

        OrderDao orderDao = new OrderDaoImpl();
        orderDao.insertOrder(order);
        System.out.println(order.toString());

        CarDao carDao = new CarDaoImpl();
        List<Car> carList = carDao.selectCarsByUserno(Integer.parseInt(userno));
        List<Item> items = new ArrayList<>();
        for (Car car:carList){
            Item item = new Item();
            item.setOid(orderId);
            item.setGid(car.getGid());
            item.setNumber(car.getNumber());
            item.setCount(car.getCount());
            items.add(item);
        }

        orderDao.insertItems(items);
        carDao.deleteCarByCid(userno);


    }

    @Override
    public List<Order> findOrders(int userno) {
        OrderDao orderDao = new OrderDaoImpl();
        List<Order> list = orderDao.selectOrderByUserno(userno);
        return list;
    }

    @Override
    public Order findOrderByOid(String oid) {
        OrderDao orderDao = new OrderDaoImpl();
        Order order = orderDao.selectOrderByOid(oid);
        List<Item> items = orderDao.selectItemsByOid(oid);
        order.setItems(items);
        return order;
    }
}
